/*
	Copyright (c) 2009-2011, Stefan Webb.

	This file is part of SimpleML. Please read the file "license.txt", 
	which contains the conditions under which this software is distributed.
*/

/*!
	\file text.h
	\author Stefan Webb
	\brief Definition of Text class and related enumeration.
*/

#ifndef TEXT_H
#define TEXT_H

/*! \brief Enumeration of supported encoding types. */
enum Encoding {
	ASCII, UTF16, UTF16BE, UTF8
};

/*! \brief Text class, that will read a plain text file in a number of formats, and
		convert it to UTF16, so different formats can be handled uniformly by an application. */
class  Text : public Agent, public String<utf16> //__declspec( dllexport)
{
public:
	/*! \brief Default constructor. */
	Text();

	/*! \brief Constructor with filename to open. */
	Text(utf16*);

	/*! \brief Default destructor. */
	~Text();

	/*! \brief Open filename and convert to UTF16. 
		\param filename File to open.
		\return True if operation succeeds. False, otherwise. */
	bool open(wchar_t* filename);
	
	/*! \brief Frees the memory and zeros the pointers. */
	void close();

	/*! \brief We need to overide destroy. */
	void destroy();

	/*! \brief Return pointer to string.
		\return Pointer to string. */
	utf16* string(void);

	/*! \brief Get string element, without bounds check (for speed).
		\param i Index to element.
		\return The i-th element. */
	utf16& operator[](unsigned int i);

	/*! \brief Determine size of text.
		\return Size of text in utf16 characters. */
	unsigned int size();

	/* Returns a pointer to the string */
	utf16* getLine(unsigned int linenumber);

	/* Returns lines */
	utf16** getLines();

	/* Breaks the text file into lines if necessary and then returns how many lines there are */
	unsigned int countLines();

	/* Sort lines */
	void sortLines();

private:
	/*! \brief Initialize variables. */
	void initialize();

	/* Splits the file string into an array of lines */
	void splitLines();

	unsigned int nextLine(utf16* text, unsigned int i);

	unsigned int whatNewLine(utf16* f, int i);

	/*! \brief Detects the encoding of a filebuffer if it is a text file. */
	Encoding detectEncoding(unsigned char*);

	/*! \brief Converts from UTF8 to UTF16. */
	utf16* UTF8toUTF16(unsigned char*);

	/*! \brief Converts from ASCII to UTF16. */
	utf16* ASCIItoUTF16(unsigned char*, int);

	/*! \brief Converts from big-endian UTF16 to little-endian UTF16. */
	utf16* UTF16BEtoUTF16(unsigned char*);

	/*! \brief Pointer to text string of file. */
	utf16* text_;

	/*! \brief Length of text string in wide characters. */
	unsigned int length_;

	/*! \brief File object for text file. */
	File file_;

	/*! \brief Buffer containing text file. */
	char* buffer_;

	/*! \brief Size of buffer in bytes. */
	unsigned int size_;

	/* TODO: Description. */
	utf16** lines;

	/* TODO: Description. */
	unsigned int numberlines;
};

#endif